#include <QtWidgets/QMainWindow>
#include <QtWidgets/QWidget>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QLabel>
#include <QtWidgets/QApplication>

class MainWindow : public QMainWindow {
public:
    MainWindow(QWidget *parent = nullptr) : QMainWindow(parent) {
        // 创建中心小部件和布局
        centralWidget = new QWidget(this);
        gridLayout = new QGridLayout(centralWidget);

        // 初始化布局
        updateLayout();

        // 设置中心小部件并应用布局
        setCentralWidget(centralWidget);
    }

    void addWidget(QString widgetName, QString description) {
        // 创建新的小部件
        QPushButton *button = new QPushButton(widgetName, this);
        QLabel *label = new QLabel(description, this);

        // 计算下一个小部件应该放置的位置
        int rowCount = gridLayout->rowCount();
        int colCount = gridLayout->columnCount();

        // 假设每行放两列元素，偶数列为按钮，奇数列为描述标签
        int buttonCol = (rowCount * 2) % (colCount * 2);
        int labelCol = buttonCol + 1;

        // 添加到网格布局
        gridLayout->addWidget(button, rowCount, buttonCol);
        gridLayout->addWidget(label, rowCount, labelCol);

        // 需要时增加新行
        if(labelCol + 1 >= colCount * 2) {
            gridLayout->setRowMinimumHeight(rowCount + 1, button->sizeHint().height());
        }
    }

private:
    QWidget *centralWidget;
    QGridLayout *gridLayout;

    void updateLayout() {
        // 可以根据需要初始化布局或添加其他小部件
    }
};

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);
    MainWindow mainWindow;
    mainWindow.show();

    // 动态添加小部件作为演示
    mainWindow.addWidget("Button 1", "This is a description for Button 1");
    mainWindow.addWidget("Button 2", "This is a description for Button 2");
    // ...此处可以根据需求继续添加更多小部件

    return app.exec();
}